<?php
//by willson 105328468@qq.com 2014/10/11
//index page interface

class order extends core {
	private $order_mod;
	private $commission_mod;

	public function __construct() {
		parent::__construct();
		$this->order_mod = m("order");
		$this->commission_mod = m("commission");
	}

	//订单列表
	public function index() {
	    //查找是否有显示电话号码权限
        $xian = SQL::share('admin_permission')->where("app='all' AND act='phone' AND admin_id='{$this->admin_id}'")->row();

		// $total_price = $paid_price = $yue_paid_price = $completed_price = 0;
		$where = '';
		$export = $this->request->get('export', 0);
		$status = (isset($_GET['status'])) ? trim($_GET['status']) : '';
		$city = (isset($_GET['city'])) ? trim($_GET['city']) : '';
		$differ_status = (isset($_GET['differ_status'])) ? trim($_GET['differ_status']) : '';
		$keyword = (isset($_GET['keyword']) && trim($_GET['keyword'])) ? trim($_GET['keyword']) : '';
		$order_id = (isset($_GET['order_id'])) ? trim($_GET['order_id']) : '';
		$shop_id = (isset($_GET['shop_id'])) ? intval($_GET['shop_id']) : 0;
		$pay_method = (isset($_GET['pay_method'])) ? trim($_GET['pay_method']) : '';
		$integral_order = (isset($_GET['integral_order'])) ? intval($_GET['integral_order']) : 0;
		if ($keyword) {
			$where .= " AND (order_sn LIKE '%{$keyword}%' OR mp.name LIKE '%{$keyword}%' OR o.mobile LIKE '%{$keyword}%'
				OR o.address LIKE '%{$keyword}%' OR mp.idcard LIKE '%{$keyword}%' )";
		}
		if (strlen($city)) {
			$city_id = intval(SQL::share("city")->where("name LIKE '%{$city}%'")->val("city_id"));
			if ($city_id) $where .= " AND o.city='{$city_id}'";
		}
		if (strlen($status)) {
			$where .= " AND o.status IN ({$status})";
		}
		if (strlen($differ_status)) {
			if (intval($differ_status)==0) {
				$where .= " AND o.differ_money>0 AND o.differ_pay_time=0";
			} else {
				$where .= " AND o.differ_pay_time>0";
			}
		}
		if (strlen($order_id)) {
			$where .= " AND o.id='{$order_id}'";
		}
		if ($shop_id) {
			$where .= " AND o.shop_id='{$shop_id}'";
		}
		if (strlen($pay_method)) {
			$where .= " AND o.pay_method='{$pay_method}'";
		}
		$where .= " AND o.integral_order='{$integral_order}'";
		//分页
		$this->setpages(array('order_id'=>$order_id, 'city'=>$city, 'keyword'=>$keyword, 'status'=>$status,
			 'shop_id'=>$shop_id, 'pay_method'=>$pay_method, 'integral_order'=>$integral_order
			));
		$sql = "SELECT o.* , mp.name as canbao_name, mp.idcard as canbao_idcard, 
			m.nick_name as member_name, c.name as city_name, '' as status_name 
			FROM {$this->tbp}order o
			LEFT JOIN {$this->tbp}member m ON o.member_id = m.id 
			LEFT JOIN {$this->tbp}member_person mp ON o.person_id = mp.id 
			LEFT JOIN {$this->tbp}city c ON o.city = c.city_id 
			WHERE 1 {$where} ORDER BY o.id DESC";
		$rs = $this->ezr->get_results($sql);
		if ($rs) {
			foreach ($rs as $key => $row) {
				$rs[$key]['status_name'] = $this->order_mod->status_name($row['status']);
				if ($row['add_time']) $rs[$key]['add_time'] = date("Y-m-d H:i:s", $row['add_time']);
				if ($row['pay_time']) $rs[$key]['pay_time'] = date("Y-m-d H:i:s", $row['pay_time']);
                $rs[$key]['remark'] = mb_substr($row['remark'],0,10,"UTF-8");
                if (empty($xian)){
                    $xing = substr($row['mobile'],4,4);  //获取手机号中间四位
                    $rs[$key]['mobile'] = str_replace($xing,'****',$row['mobile']);  //用****进行替换
                }
			}
		}
		if ($export>0) {
			export_excel($rs, array(
				'id'=>'ID',
				'order_sn'=>'订单号',
				'member_name'=>'下单人',
				'name'=>'收货人',
				'mobile'=>'电话',
				'address'=>'地址',
				'add_time'=>'下单时间',
				'pay_time'=>'支付时间',
				'total_price'=>'订单总价',
				'pay_method'=>'支付方式',
				'status_name'=>'订单状态'
			));
		}
		$nav = $this->ezr->get_navigation();
		$this->smarty->assign('rs',$rs);
		$this->smarty->assign('status',$status);
		$this->smarty->assign('differ_status',$differ_status);
		$this->smarty->assign('keyword',$keyword);
		$this->smarty->assign('shop_id',$shop_id);
		$this->smarty->assign('order_id',$order_id);
		$this->smarty->assign('pay_method',$pay_method);
		$this->smarty->assign('integral_order',$integral_order);
		$this->smarty->assign('page',$nav);
		$this->smarty->assign('where',$where);
		$this->display();
	}

	//获取查询条件下的订单金额
	private function _get_total_price($order_status, $where) {
		$sql = "SELECT sum(total_price)
			FROM {$this->tbp}order o LEFT JOIN im_beautician b ON o.beautician_id=b.id
			LEFT JOIN {$this->tbp}beautyshop s ON o.shop_id=s.id
			LEFT JOIN {$this->tbp}member_cash_coupon mcc ON o.member_cash_coupon_id=mcc.id
			WHERE o.status IN ({$order_status}) AND o.pay_method<>'yue' {$where}";
		$price = floatval($this->db->get_var($sql));
		$price = number_format($price, 2);
		return $price;
	}

	//余额支付
	private function _get_yue_pay_total_price($order_status, $where) {
		$sql = "SELECT sum(total_price)
			FROM {$this->tbp}order o LEFT JOIN im_beautician b ON o.beautician_id=b.id
			LEFT JOIN {$this->tbp}beautyshop s ON o.shop_id=s.id
			LEFT JOIN {$this->tbp}member_cash_coupon mcc ON o.member_cash_coupon_id=mcc.id
			WHERE o.status IN ({$order_status}) AND o.pay_method='yue' {$where}";
		$price = floatval($this->db->get_var($sql));
		$price = number_format($price, 2);
		return $price;
	}

	//详情
	public function edit() {
		if (IS_POST) {
			$this->save();
		} else {
            //查找是否有显示电话号码权限
            $xian = SQL::share('admin_permission')->where("app='all' AND act='phone' AND admin_id='{$this->admin_id}'")->row();

			$id = (isset($_GET['id']) && intval($_GET['id'])) ? intval($_GET['id']) : 0;
			$sql = "SELECT o.*,m.nick_name as member_name ,m.id as member_id
				FROM {$this->tbp}order o LEFT JOIN {$this->tbp}member m ON o.member_id = m.id
				WHERE o.id='{$id}'";
			//echo $sql;
			$row = $this->db->get_row($sql);
			if (!$row) $this->error('记录不存在');
			//$row->status_name = $this->order_mod->status_name($row->status);
			if ($row->coupon_sn!='') {
				$sql = "SELECT coupon_id FROM {$this->tbp}coupon_sn WHERE sn='{$row->coupon_sn}'";
				$row->coupon_id = intval($this->db->get_var($sql));
			}
            if ($row){
                if (empty($xian)){
                    $xing = substr($row->mobile,4,4);  //获取手机号中间四位
                    $row->mobile = str_replace($xing,'****',$row->mobile);  //用****进行替换
                    //var_dump($data);exit();
                }
            }
			$this->smarty->assign('row',$row);
			
			$sql = "SELECT og.*, s.name as shop_name FROM {$this->tbp}order_goods og
				LEFT JOIN {$this->tbp}shop s ON og.shop_id=s.id WHERE og.order_id={$id}";
			$goods = $this->db->get_results($sql);
			if ($goods) {
				foreach ($goods as $k=>$g) {
					if (is_numeric($g->spec)) {
						$sql = "SELECT spec FROM {$this->tbp}goods_spec WHERE id='{$g->spec}'";
						$goods[$k]->spec = $this->db->get_var($sql);
					}
				}
			}
			$this->smarty->assign('goods',$goods);
			
			$months = explode(',', $row->month);
			$person = SQL::share('member_person')->where($row->person_id)->row();

			$service_city = SQL::share('service_city')->where("city_id='{$row->city}'")->row('service_money');
			$province = SQL::share('province')->where("province_id='{$row->province}'")->val('name');
			$city = SQL::share('city')->where("city_id='{$row->city}'")->val('name');
			
			$rs = SQL::share('service_casy_detail')->where("casy_id='{$row->casy_id}'")
				->find('*, TRUNCATE(money*(firm/100),2) as firm_money, TRUNCATE(money*(person/100),2) as person_money');
			$total_price = $total = $gjj_total = $firm_total = $person_total = 0;
			if ($rs) {
				foreach ($rs as $k=>$g) {
					$firm_total = bcadd($firm_total, $g->firm_money, 2);
					$person_total = bcadd($person_total, $g->person_money, 2);
				}

				$casy = SQL::share('service_city sc')->left('service_casy c', 'sc.id=service_city_id')
					->where("c.id='{$row->casy_id}'")->row('sc.money, sc.firm, sc.person');
				$gjj = new stdClass();
				$gjj->name = '公积金';
				$gjj->money = $casy->money;
				$gjj->firm = $casy->firm;
				$gjj->person = $casy->person;
				$gjj->firm_money = strval(round($gjj->money*($gjj->firm/100),2));
				$gjj->person_money = strval(round($gjj->money*($gjj->person/100),2));
				$total = bcmul(bcadd($firm_total, $person_total, 2), count($months), 2);
				$gjj_total = bcmul(bcadd($gjj->firm_money, $gjj->person_money, 2), count($months), 2);
				$total_price = bcadd($total, $gjj_total, 2);
			}
			$service_money = bcmul($service_city->service_money, count($months), 2);
			$data = array('name'=>$person->name, 'idcard'=>$person->idcard, 'idcard_pic1'=>$person->idcard_pic1, 'idcard_pic2'=>$person->idcard_pic2,
				'mobile'=>$person->mobile, 'type'=>$person->type, 'province'=>$province, 'city'=>$city,
				'service_money'=>strval(number_format($service_money,2,'.','')),
				'month'=>(count($months)>1?$months[0].' ~ '.$months[count($months)-1]:$months[0]),
				'total'=>strval(number_format($total,2,'.','')),
				'gjj_total'=>strval(number_format($gjj_total,2,'.','')),
				'total_price'=>strval(number_format($total_price,2,'.','')));

			$this->smarty->assign('info',$data);
			
			$provinces = SQL::share('province')->sort('province_id ASC')->find();
			$this->smarty->assign('provinces',$provinces);
			$citys = SQL::share('city')->sort('city_id ASC')->find();
			$this->smarty->assign('citys',$citys);
			
			$this->display();
		}
	}
	//参保方案
	public function get_casy() {
		$city_id = $this->request->get('city_id', 0);
		if ($city_id<=0) error('数据错误');
		$rs = SQL::share('service_casy sa')
			->left('service_city sc', 'service_city_id=sc.id')
			->where("sc.city_id='{$city_id}'")->sort('sa.id ASC')->find('sa.*');
		success($rs);
	}

	//保存
	public function save() {
		$update_sql = '';
		$shipping_time = '';
		$shouhuo_time = '';
		$differ_pay_time = '';
		$id = (isset($_POST['id']) && intval($_POST['id'])) ? intval($_POST['id']) : 0;
		$total_price = (isset($_POST['total_price']) && floatval($_POST['total_price'])) ? floatval($_POST['total_price']) : 0;
		$address = (isset($_POST['address']) && trim($_POST['address'])) ? trim($_POST['address']) : '';
		$shipping_company = (isset($_POST['shipping_company']) && trim($_POST['shipping_company'])) ? trim($_POST['shipping_company']) : '';
		$shipping_number = (isset($_POST['shipping_number']) && trim($_POST['shipping_number'])) ? trim($_POST['shipping_number']) : '';
		$shipping_price = (isset($_POST['shipping_price']) && trim($_POST['shipping_price'])) ? trim($_POST['shipping_price']) : '';
		$print = (isset($_POST['print']) && trim($_POST['print'])) ? intval($_POST['print']) : 0;
		$status = isset($_POST['status']) ? intval($_POST['status']) : -1;
		$oldstatus = isset($_POST['oldstatus']) ? intval($_POST['oldstatus']) : -1;
		$readed = isset($_POST['readed']) ? intval($_POST['readed']) : 0;
		$price = isset($_POST['price']) ? $_POST['price'] : '';
		$goods_id = isset($_POST['goods']) ? $_POST['goods'] : '';
		$province = (isset($_POST['province']) && intval($_POST['province'])) ? intval($_POST['province']) : 0;
		$city = (isset($_POST['city']) && intval($_POST['city'])) ? intval($_POST['city']) : 0;
		$casy_id = (isset($_POST['casy_id']) && intval($_POST['casy_id'])) ? intval($_POST['casy_id']) : 0;
		$remark = isset($_POST['remark']) ? $_POST['remark']: '';
		
		$gjj_total = $this->request->post('gjj_total', 0, 'float');
		$service_money = $this->request->post('service_money', 0, 'float');
		$service_money_total = $this->request->post('service_money_total', 0, 'float');
		$differ_money = $this->request->post('differ_money', 0, 'float');
		//获取发货时间，用来判断之前是否已经发货
		$sql = "SELECT member_id, shipping_time, order_sn FROM {$this->tbp}order WHERE id='{$id}'";
		$is_shipping = $this->db->get_row($sql);
		//更改是否阅读
		if ($status>=0 && $status<4 && $status!==$oldstatus) {
			$readed = 1;
		}
		//发货时间
		if ($status==2) {
			//$shipping_time = ", shipping_time='".time()."'";
		}
		if ($status==3) {
			$shouhuo_time = ", shouhuo_time='".time()."'";
		}
		if ($differ_money>0) {
			$differ_pay_time = ", differ_pay_time='0'";
		}
		//更新订单信息
		$sql = "UPDATE {$this->tbp}order SET address='{$address}', total_price='{$total_price}', status='{$status}',
			shipping_company='{$shipping_company}', shipping_number='{$shipping_number}', remark='{$remark}',
			readed='{$readed}', province='{$province}', city='{$city}', casy_id='{$casy_id}',
			gjj_total='{$gjj_total}', service_money='{$service_money}', service_money_total='{$service_money_total}',
			differ_money='{$differ_money}' {$differ_pay_time} {$shipping_time} {$shouhuo_time}
			WHERE id='{$id}'";
		//var_dump($sql);exit;
		$this->db->query($sql);
		/*
		if ($price) {
			foreach ($price as $i=>$v) {
				foreach ($goods_id as $k=>$g) {
					if ($i==$k) {
						$sql = "UPDATE {$this->tbp}order_goods SET price='{$v}' WHERE order_id='{$id}' AND id='{$g}'";
						$this->db->query($sql);
					}
				}
			}
		}
		*/
		//订单佣金转账到会员的佣金
		if ($status>=3 && $id>0) {
			// print_r($status);exit;
			//$this->commission_mod->turn_commission($id);
		}
		//退回佣金
		if ($status<0) {
			//$this->commission_mod->cancel($id);
		}

		//发货状态发送物流消息通知
		if ($is_shipping->shipping_time==0 && $shipping_company && $shipping_number) {
			//$this->save_message("您的订单{$is_shipping->order_sn}已经发货，物流信息请从订单详情查看。", $is_shipping->member_id, 'logistics');
		}

		if ($print>0) {
			header("Location:?app=order&act=print_order&order_id={$id}");
		} else {
			header("Location:?app=order&act=index");
		}
	}

	//删除
	public function delete() {
		$this->permission($this->admin_id, $this->app, $this->act);
		$id = (isset($_GET['id']) && trim($_GET['id'])) ? intval($_GET['id']) : 0;
		$sql = "DELETE FROM {$this->tbp}order WHERE id='{$id}'";
		$this->db->query($sql);
		header("Location:?app=order&act=index");
	}
	//发货单
	public function print_order(){
		$id = (isset($_GET['order_id']) && trim($_GET['order_id'])) ? intval($_GET['order_id']) : 0;
		$sql = "SELECT o.*,m.name as member_name FROM {$this->tbp}order o LEFT JOIN {$this->tbp}member m ON o.member_id = m.id
			WHERE o.id = {$id} ORDER BY o.id DESC";
		$row = $this->db->get_row($sql);
		$sql ="SELECT g.*,s.name as shop_name FROM {$this->tbp}order_goods g LEFT JOIN {$this->tbp}shop s ON g.shop_id =s.id
			WHERE g.order_id = {$id}";
		$goods = $this->db->get_results($sql);
		$total = 0;
		$i = 0;
		foreach ($goods as  $value) {
			$i =$value->sort= $i + 1;
			$total = $value->quantity +$total;
		}
		$this->smarty->assign('total',$total);
		$this->smarty->assign('goods',$goods);
		$this->smarty->assign('row',$row);
		$this->display();
	}

	public function return_goods(){
		$where = '';
		$id = (isset($_GET['id']) && trim($_GET['id'])) ? intval($_GET['id']) : '';
		$keyword = (isset($_GET['keyword']) && trim($_GET['keyword'])) ? trim($_GET['keyword']) : '';
		if ($keyword) {
			$where .= "AND (m.name LIKE '%{$keyword}%' OR m.real_name LIKE '%{$keyword}%' OR m.mobile LIKE '%{$keyword}%')";
		}
		if ($id) {
			$where .= "AND r.id='{$id}'";
		}
		//分页
		$this->setpages(array('id'=>$id, 'keyword'=>$keyword));
		
		$sql = "SELECT r.*, o.order_sn, m.name, m.real_name, m.mobile FROM {$this->tbp}order_refund r
			LEFT JOIN {$this->tbp}order o ON r.order_id=o.id
			LEFT JOIN {$this->tbp}member m ON r.member_id=m.id
			WHERE 1 {$where} ORDER BY r.id DESC, r.status ASC";
		$rs = $this->ezr->get_results($sql);
		if ($rs) {
			foreach ($rs as $k=>$g) {
				$rs[$k]['name'] = strlen($g['name']) ? $g['name'] : $g['mobile'];
			}
		}
		$nav = $this->ezr->get_navigation();
		$this->smarty->assign('rs',$rs);
		$this->smarty->assign('page',$nav);
		$this->display();
	}
	public function return_edit(){
		$id = (isset($_GET['id']) && trim($_GET['id'])) ? intval($_GET['id']) : 0;
		$sql = "SELECT r.*, o.order_sn, m.name, m.name, m.real_name,  m.mobile FROM {$this->tbp}order_refund r
			LEFT JOIN {$this->tbp}order o ON r.order_id=o.id
			LEFT JOIN {$this->tbp}member m ON r.member_id=m.id
			WHERE r.id={$id}";
		$row = $this->db->get_row($sql);
		if ($row) {
			$row->name = strlen($row->name) ? $row->name : $row->mobile;
		}
		$this->smarty->assign('row',$row);
		$this->display();
	}
	//删除
	public function return_goods_delete() {
		$id = (isset($_GET['id']) && trim($_GET['id'])) ? intval($_GET['id']) : 0;
		$order_id = (isset($_GET['order_id']) && trim($_GET['order_id'])) ? intval($_GET['order_id']) : 0;
		$sql = "DELETE FROM {$this->tbp}order_refund WHERE id='{$id}' OR order_id='{$order_id}'";
		$this->db->query($sql);
		header("Location:?app=order&act=return_goods");
	}
	
	//第三方退款
	private function _refund($order_id, $order_sn, $trade_no, $total_price, $pay_method, $out_refund_no, $refund_id, $member_id=0, $mobile='') {
		if ($pay_method=='yue') {
			$sql = "UPDATE {$this->tbp}member SET money=money+{$total_price} WHERE id='{$member_id}'";
			$this->db->query($sql);
			$sql = "UPDATE {$this->tbp}order_refund SET status='1' WHERE id='{$refund_id}'";
			$this->db->query($sql);
			$sql = "UPDATE {$this->tbp}order SET status='-2' WHERE id='{$order_id}'";
			$this->db->query($sql);
		} else {
			$sql = "UPDATE {$this->tbp}order_refund SET status='1' WHERE id='{$refund_id}'";
			$this->db->query($sql);
			$sql = "UPDATE {$this->tbp}order SET status='-2' WHERE id='{$order_id}'";
			$this->db->query($sql);
		}
	}
	private function _refund2($order_id, $order_sn, $trade_no, $total_price, $pay_method, $out_refund_no, $refund_id, $member_id=0, $mobile='') {
		if ($pay_method=='wxpay' || $pay_method=='wxpay_h5') {
			if ($pay_method=='wxpay') {
				include_once(FRAMEWORK_PATH . "/class/wxapi/RefundAppHelper/WxPay.Api.php");
			} else {
				include_once(FRAMEWORK_PATH . "/class/wxapi/RefundWxHelper/WxPay.Api.php");
			}
			$input = new WxPayRefund();
			if ($trade_no!='') {
				$input->SetTransaction_id($trade_no); //微信订单号
			} else {
				$input->SetOut_trade_no($order_sn); //原订单号
			}
			$input->SetTotal_fee($total_price*100); //订单金额，单位分
			$input->SetRefund_fee($total_price*100); //退款金额
			$input->SetOp_user_id(WxPayConfig::MCHID); //操作员账号，一般为商户号
			$input->SetOut_refund_no($out_refund_no); //退款订单号
			$data = WxPayApi::refund($input);
			//foreach ($data as $k=>$v) echo "<font color='#f00;'>$k</font> : $v<br/>";exit;
			if ($data["return_code"]=='SUCCESS') {
				if ($data["result_code"]=='SUCCESS') {
					$sql = "UPDATE {$this->tbp}order_refund SET status='1' WHERE id='{$refund_id}'";
					$this->db->query($sql);
					$sql = "UPDATE {$this->tbp}order SET status='-2' WHERE id='{$order_id}'";
					$this->db->query($sql);
				} else {
					error($data["err_code_des"]);
				}
			} else {
				error($data["return_msg"]);
			}
		} else if ($pay_method=='alipay') {
			require_once(FRAMEWORK_PATH . "/class/alipay/alipay.config.php");
			require_once(FRAMEWORK_PATH . "/class/alipay/lib/alipay_refund_nopwd_service.php");
			$seller_email = $alipay_config['seller_email']; //卖家支付宝帐户
			$refund_date = date('Y-m-d H:i:s'); //退款当天日期
			$batch_no = date('YmdHis'); //批次号, 格式：当天日期[8位]+序列号[3至24位]，如：201008010000001
			$batch_num = 1; //退款笔数
			//必填，参数detail_data的值中，“#”字符出现的数量加1，最大支持1000笔（即“#”字符出现的数量999个）
			$detail_data = "{$trade_no}^{$total_price}^买家主动退款"; //退款详细数据
			//必填，具体格式请参见接口技术文档，单笔退款数据集格式：原付款支付宝交易号^退款总金额^退款理由
			$notify_url = "http://".$_SERVER['SERVER_NAME']."/notify_url_refund.php"; //异步通知页面
			//构造要请求的参数数组，无需改动
			$parameter = array(
				//接口名称，不需要修改
				"service"			=> "refund_fastpay_by_platform_nopwd",
				//获取配置文件(alipay_config.php)中的值
				"partner"			=> trim($alipay_config['partner']),
				"notify_url"		=> $notify_url,
				"_input_charset"	=> trim(strtolower($alipay_config['input_charset'])),
				//必填参数
				"refund_date"		=> $refund_date,
				"batch_no"			=> $batch_no,
				"batch_num"			=> $batch_num,
				"detail_data"		=> $detail_data
			);
			//构造请求函数, 配置环境须支持SSL
			$alipay = new alipay_refund_nopwd_service($parameter, $alipay_config['key'], $alipay_config['sign_type_refund']);
			$url = $alipay->create_url();
			$data = file_get_contents($url);
			$nodeIs_success = '';
			$nodeError_code = '';
			$obj = simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA);
			$obj = (array)$obj;
			//writeLog(json_encode($obj));
			if (isset($obj['is_success'])) $nodeIs_success = $obj['is_success']; //获取成功标识is_success
			if (isset($obj['error'])) $nodeError_code = $obj['error']; //获取错误代码 error
			if ($nodeIs_success=="T") {
				$sql = "UPDATE {$this->tbp}order_refund SET status='1' WHERE id='{$refund_id}'";
				$this->db->query($sql);
				$sql = "UPDATE {$this->tbp}order SET status='-2' WHERE id='{$order_id}'";
				$this->db->query($sql);
			} else {
				error($nodeError_code);
			}
		} else if ($pay_method=='yue') {
			$sql = "UPDATE {$this->tbp}member SET money=money+{$total_price} WHERE id='{$member_id}'";
			$this->db->query($sql);
			$sql = "UPDATE {$this->tbp}order_refund SET status='1' WHERE id='{$refund_id}'";
			$this->db->query($sql);
			$sql = "UPDATE {$this->tbp}order SET status='-2' WHERE id='{$order_id}'";
			$this->db->query($sql);
		}
	}
	//退货退款审核，1:退款, 2:退货
	public function order_check_return_goods($order_id=0, $reason='', $status=1) {
		if (!$order_id) {
			$order_id = (isset($_POST['order_id']) && trim($_POST['order_id'])) ? intval($_POST['order_id']) : 0;
			$reason = (isset($_POST['audit_memo']) && trim($_POST['audit_memo'])) ? trim($_POST['audit_memo']) : '';
			$status = (isset($_POST['status']) && trim($_POST['status'])) ? intval($_POST['status']) : 0;
		}
		if ($order_id) {
			//判断是退款还是退货
			$sql = "SELECT type FROM {$this->tbp}order_refund WHERE order_id='{$order_id}' ORDER BY id DESC";
			$type = $this->db->get_var($sql);

			$sql = "SELECT * FROM {$this->tbp}order WHERE id='{$order_id}'";
			$order = $this->db->get_row($sql);
			if ($status==1) {
				$sql = "SELECT id, out_refund_no FROM {$this->tbp}order_refund WHERE order_id='{$order_id}' ORDER BY id DESC";
				$refund = $this->db->get_row($sql);
				$this->_refund($order_id, $order->parent_order_sn, $order->trade_no, $order->total_price, $order->pay_method, $refund->out_refund_no, $refund->id, $order->member_id, $order->mobile);
				if ($type==1) {
					if (!strlen($reason)) $reason = "已退款";
				} else {
					$sql = "UPDATE {$this->tbp}order SET status='-3' WHERE id='{$order_id}'";
					$this->db->query($sql);
					$sql = "SELECT shop_id FROM {$this->tbp}order WHERE id='{$order_id}'";
					$shop_id = $this->db->get_var($sql);
					if ($shop_id) {
						$sql = "SELECT return_province, return_city, return_district, return_address, return_name, return_mobile FROM {$this->tbp}shop WHERE id='{$shop_id}'";
						$row = $this->db->get_row($sql);
						if (!strlen($reason)) $reason = "退货地址：{$row->return_province}{$row->return_city}{$row->return_district}{$row->return_address}，联系人：{$row->return_name}，电话：{$row->return_mobile}";
					} else {
						if (!strlen($reason)) $reason = '退货地址：'.$this->configs['order_refund_info'];
					}
				}
				//扣减退货退款后会员的佣金
				$this->_reduce_order_commission($order_id);
			}
			$sql = "UPDATE {$this->tbp}order_refund SET status='{$status}', audit_time='".time()."', audit_memo='{$reason}' WHERE order_id='{$order_id}'";
			$this->db->query($sql);

			//发送短信、推送
			$member_id = -1;
			$notify = '';
			$sms = array();
			$template_id = 0;
			if ($status==1) {
				if ($type==1) {
					$member_id = $order->member_id;
					$notify = "您的订单{$order->order_sn}退款成功，退款金额为{$order->total_price}元";
					$sms = array($order->order_sn, "{$order->total_price}元");
					$template_id = 221218;
				} else {
					$member_id = $order->member_id;
					$notify = "您的订单{$order->order_sn}退货成功";
					$sms = array($order->order_sn);
					$template_id = 221222;
				}
			} else {
				if ($type==1) {
					$member_id = $order->member_id;
					$notify = "您申请的退款请求失败，请联系卖家";
					$template_id = 221225;
				} else {
					$member_id = $order->member_id;
					$notify = "您申请的退货请求失败，请联系卖家";
					$template_id = 221226;
				}
			}

			$this->send_notify_sms($notify, $member_id, $sms, $template_id);

			if ($status==1 && $type==1) {
				switch ($order->pay_method) {
					case 'wxpay':
					case 'wxpay_h5':
					case 'alipay':
						//header('Location:index.php?app=order&act=return_goods');
						break;
					case 'yue':
						//header('Location:index.php?app=order&act=return_goods');
						//success('订单已退款，请在会员中心查看您的余额是否已到账');
						break;
				}
			}
		}
		header('Location:index.php?app=order&act=return_goods');
	}

	//退货退款成功后，扣减会员的佣金
	private function _reduce_order_commission($order_id) {
		$sql = "SELECT * FROM {$this->tbp}member_commission WHERE parent_id='{$order_id}' AND type=1 AND status=1";
		$rs = $this->db->get_results($sql);
		if ($rs) {
			foreach ($rs as $k => $g) {
				$money = $g->commission;
				if ($money) {
					//处理店铺佣金
					$sql = "SELECT shop_id FROM {$this->tbp}order WHERE id='{$g->parent_id}'";
					$order = $this->db->get_row($sql);
					if ($order) {
						$sql = "SELECT total_income, can_withdraw_money, member_id FROM {$this->tbp}shop WHERE id='{$order->shop_id}'";
						$shop = $this->db->get_row($sql);
						if ($shop) {
							if ($shop->total_income>=$money) {
								$shop->total_income = $shop->total_income - $money;
							} else {
								$shop->total_income = 0;
							}
							if ($shop->can_withdraw_money>=$money) {
								$shop->can_withdraw_money = $shop->can_withdraw_money - $money;
							} else {
								$shop->can_withdraw_money = 0;
							}
							$sql = "UPDATE {$this->tbp}shop SET total_income='{$shop->total_income}',
								can_withdraw_money='{$shop->can_withdraw_money}' WHERE id='{$order->shop_id}'";
							$this->db->query($sql);
							//处理会员佣金
							$sql = "SELECT commission FROM {$this->tbp}member WHERE id='{$shop->member_id}'";
							$member = $this->db->get_row($sql);
							if ($member) {
								if ($member->commission>=$money) {
									$member->commission = $member->commission - $money;
								} else {
									$member->commission = 0;
								}
								$sql = "UPDATE {$this->tbp}member SET commission='{$member->commission}' WHERE id='{$shop->member_id}'";
								$this->db->query($sql);
							}
						}
					}
				}
			}
		}
		$sql = "UPDATE {$this->tbp}member_commission SET status='-1' WHERE parent_id='{$order_id}' AND type=1";
		$this->db->query($sql);
	}

}
